<template>
    <div style="margin-top: 30px;padding: 40px 200px">
        <div v-if="carIds.length<=0">
            <a-result title="您尚未选择任何商品或购物车记录失效">
                <template #extra>
                    <a-button key="console" type="primary" @click="toShoppingCar">
                        返回购物车
                    </a-button>
                </template>
            </a-result>
        </div>
        <div v-else>
            <a-row>
                <a-col :span="3" :offset="1">
                    <div>
                        <img style="width: 100px;height: 100px;"
                             src="http://120.27.212.10:9090/group1/M00/00/00/eBvUCl_ZdgmAGkv5AAJJ7HtejHk284.png">
                    </div>
                </a-col>
                <a-col :span="20" style="margin-top: 40px">
                    <span style="font-size: 26px;font-weight: 400">结算页</span>
                </a-col>
            </a-row>

            <!--收货地址选择-->
            <div class="address-header-text">选择收货地址</div>
            <a-row>
                <a-col :span="6" v-for="(address,index) in addressList" style="margin:0px 10px 15px 0px"
                       v-show="index<=3 || showAllAddress===true">
                    <div class="address-card" @click="selectAddress(address)">
                        <div style="z-index: 4;float: right;background: transparent;margin-right: 5px"
                             v-if="address.isDefault===true">
                            默认地址
                        </div>
                        <a-row class="address-area">
                            {{address.province}}{{address.city}}（{{address.name}}收）
                        </a-row>
                        <a-row style="margin-top: 10px">
                            {{address.province}} {{address.city}} {{address.area}} {{address.address}}
                            {{address.mobile}}
                        </a-row>
                        <a-row style="float: bottom">
                            <a style="color: #fa9b9e;font-size: 14px" @click="openAddressForm(address)">修改</a>
                        </a-row>
                        <right-bottom-triangle v-if="selectedAddress&&selectedAddress.id===address.id"/>
                    </div>
                </a-col>
            </a-row>
            <div class="showAll">
                <a v-if="showAllAddress===false&&addressList.length>4" @click="showAllAddress=true">显示全部地址</a>
                <a v-if="showAllAddress===true" @click="showAllAddress=false">收起</a>
            </div>
            <span style="color: red;font-size: 12px">商品价格可能与添加购物车时的价格有出入，以当前价格为准</span>
            <div class="address-header-text">确认订单信息</div>
            <a-row>
                <a-card style="width: 900px;background: #FBFCFF"
                        v-for="(order,oindex) in confirmOrderData.confirmOrderList">
                    <div class="shopName">店铺：{{order.shopName}}</div>
                    <a-row :gutter="[24,58]" v-for="(goods,goodsIndex ) in order.goodsList">
                        <a-col :span="2">
                            <img style="width: 60px;height: 60px" :src="goods.picture"/>
                        </a-col>
                        <a-col :span="10">
                            <div class="goodsName">
                                {{goods.name}}
                            </div>

                        </a-col>
                        <a-col :span="5">
                            <div>
                            <span class="goodsName">
                               {{goods.specStr}}
                            </span>
                            </div>
                        </a-col>
                        <a-col :span="2">
                            <span>￥{{goods.price}}</span>
                        </a-col>
                        <a-col :span="2">
                            <span style="margin-left: 15px">x {{goods.num}}</span>
                        </a-col>
                        <a-col :span="2">
                            <span class="price">￥{{goods.totalPrice}}</span>
                        </a-col>

                    </a-row>
                    <a-row style="margin-top: 10px">
                        <a-col :span="7">
                            <label style="font-size: 14px">给卖家留言：</label>
                            <a-textarea placeholder="选填，请先和商家协商一致" v-model="order.message"></a-textarea>
                            <span class="tip" v-if="showMessage">不能超过200字</span>
                        </a-col>
                        <a-col :span="8" :offset="4">
                            <a-row :gutter="[24,24]" v-if="order.couponList&&order.couponList.length>0">
                                <a-col :span="8">
                                    店铺优惠：
                                </a-col>
                                <a-col :span="16">
                                    <a-select class="coupon-select" placeholder="优惠信息"
                                              :defaultValue="couponMax[oindex]"
                                              @change="value=>shopCouponChange(value,order.shopId)">
                                        <a-select-option value="-1">
                                            不使用优惠
                                        </a-select-option>
                                        <a-select-option :value="coupon.couponId" v-for="coupon in order.couponList"
                                                         :disabled="useSysCoupon"
                                        >
                                            <a-tooltip placement="right">
                                                <template slot="title">
                                                    <span>省 {{coupon.discount}} 元：{{coupon.what===1?coupon.min+'-'+coupon.discount:'立减'+coupon.discount+'元'}}</span>
                                                </template>
                                                <span>省 {{coupon.discount}} 元：{{coupon.what===1?coupon.min+'-'+coupon.discount:'立减'+coupon.discount+'元'}}</span>
                                            </a-tooltip>

                                        </a-select-option>
                                    </a-select>
                                </a-col>
                            </a-row>
                            <a-row :gutter="[24,24]">
                                <a-col :span="8">
                                    运送方式：
                                </a-col>
                                <a-col :span="16">
                                    普通配送 快递 免邮
                                </a-col>
                            </a-row>
                            <a-row>
                                <a-col :span="8">
                                    是否开发票：
                                </a-col>
                                <a-col :span="16">
                                    <a-checkbox v-model="order.invoice"></a-checkbox>
                                </a-col>
                            </a-row>
                        </a-col>
                        <a-col :span="3" :offset="2">
                            <div style="margin-left: 17px">
                                <span class="price">- {{order.coupon.couponId?order.coupon.discount:'0.00'}}</span>
                            </div>
                        </a-col>

                    </a-row>
                    <a-row>
                        <a-col :span="14"></a-col>
                        <a-col :span="6" :offset="4">
                            <span style="margin-left: 8px">店铺合计： <span class="price">￥ {{order.totalPrice-(order.coupon.couponId?order.coupon.discount:0)}}</span></span>
                        </a-col>
                    </a-row>
                </a-card>
                <div class="integral-checkbox">
                    <a-row :gutter="[0,24]">
                        <a-col :span="15"></a-col>
                        <a-col :span="5">
                            <a-checkbox v-if="confirmOrderData.integral&&confirmOrderData.integral>0"
                                        @change="useIntegralChange" style="  font-size: 13px;color: #333;">
                                使用积分{{confirmOrderData.integral}}个
                            </a-checkbox>
                        </a-col>
                        <a-col v-if="confirmOrderData.integral&&confirmOrderData.integral>0" :span="3" offset="0">
                            <span class="price">- ￥{{useIntegral?confirmOrderData.integral/100:'0.00'}}</span>
                        </a-col>
                    </a-row>
                    <a-row v-if="confirmOrderData.sysCouponList&&confirmOrderData.sysCouponList.length>0">
                        <a-col :span="13"></a-col>
                        <a-col :span="3">
                            系统优惠：
                        </a-col>
                        <a-col :span="4">

                            <a-select class="coupon-select" placeholder="优惠信息"
                                      @change="value=>sysCouponChange(value)" defaultValue="-1">
                                <a-select-option value="-1">
                                    不使用优惠
                                </a-select-option>
                                <a-select-option :value="sysCoupon.couponId" :disabled=" useShopCoupon"
                                                 v-for="sysCoupon in confirmOrderData.sysCouponList"
                                >
                                    <a-tooltip placement="right">
                                        <template slot="title">
                                            <span>省 {{sysCoupon.discount}} 元：{{sysCoupon.what===1?sysCoupon.min+'-'+sysCoupon.discount:'立减'+sysCoupon.discount+'元'}}</span>
                                        </template>
                                        <span>省 {{sysCoupon.discount}} 元：{{sysCoupon.what===1?sysCoupon.min+'-'+sysCoupon.discount:'立减'+sysCoupon.discount+'元'}}</span>
                                    </a-tooltip>

                                </a-select-option>
                            </a-select>
                        </a-col>
                        <a-col :span="3">
                            <span class="price">- ￥{{sysCoupon.couponId?sysCoupon.discount:'0.00'}}</span>
                        </a-col>
                    </a-row>
                </div>
            </a-row>
            <div class="commit-contaniner">
                <div>
                    <a-row>
                        <a-col :span="17"></a-col>

                        <a-col :span="7">
                            <span style="color: red;">{{goodsCount}}</span> 件商品

                            <span class="commit-title">实付款</span>： <span
                                style="font: 700 26px tahoma;color: #FF465C">￥{{orderTotalPrice}}</span>
                        </a-col>
                    </a-row>
                    <a-row>
                        <div style="width: 900px;margin-left: 250px">
                            <span class="commit-title">寄送至</span>：<span
                                class="address-info">{{selectedAddress.province}} {{selectedAddress.city}} {{selectedAddress.area}} {{selectedAddress.address}}</span>
                            <span>
                        <span class="commit-title">收货人</span>：<span class="address-info">{{selectedAddress.name}} {{selectedAddress.mobile}}</span>
                    </span>
                        </div>
                    </a-row>
                </div>
            </div>
            <div style="width: 900px;">
                <div>
                    <span class="commit-btn" @click="commitOrder">提交订单</span>
                </div>
            </div>
            <address-form :address-model-visible="addressModelVisible" :address-form="addressForm"
                          @modifyAreas="modifyAreas" @closeForm="closeForm"></address-form>
        </div>
    </div>
</template>

<script>
    import RightBottomTriangle from "../../components/icon/RightBottomTriangle";
    import addressApi from "../../api/info/addressApi";
    import AddressForm from "../../components/infp/address/AddressForm";
    import CouponCard from "../../components/goods/coupon/CouponCard";
    import {getUrlParam} from "../../utils/urlUtils";
    import orderApi from "../../api/order/orderApi";

    export default {
        name: "confirmOrder",
        components: {CouponCard, RightBottomTriangle, AddressForm},
        data() {
            return {
                carIds: [],//提交到此页的购物车id列表
                showAllAddress: false,
                addressList: [],
                selectedAddress: {},
                addressForm: {
                    id: undefined,
                    name: "",
                    address: "",
                    provinceId: undefined,
                    cityId: undefined,
                    areaId: undefined,
                    mobile: "",
                    zipCode: "",
                    label: "",
                    tempArea: [],
                    isDefault: false,
                },
                showMessage: false,//留言提示
                addressModelVisible: false,

                //订单数据
                confirmOrderData: {
                    confirmOrderList: [],
                    sysCouponList: [],//系统可用优惠券
                    integral: 0//当前用户积分
                },
                goodsCount: 0,//订单商品总数
                orderTotalPrice: 0,//订单总价（未计算优惠）
                sysCoupon: {},//选择的系统优惠券
                useIntegral: false,//是否使用积分
                useShopCoupon: false,//是否使用店铺优惠
                useSysCoupon: false,//是否使用系统优惠
                couponMax: [],//按店铺顺序，第i个店铺的最大优惠的优惠券id，用来确定默认选中的优惠项
                orderData: {
                    order: {
                        consignee: "",//收货人
                        mobile: "",
                        address: "",
                        sysCouponId: undefined,//系统优惠券id
                        integral: 0,//积分总减免
                        useIntegral: false//是否使用了积分
                    },
                    orderShopList: []
                }//最终提交的订单数据

            }
        },
        created() {
            let urlParam = getUrlParam();
            if (urlParam && urlParam.ids) {
                this.carIds = urlParam.ids.split(",")
                console.log(this.carIds)
                this.loadAddress()
                this.loadOrder();
            }

        },
        methods: {
            commitOrder() {
                console.log(this.orderData)
                console.log(this.confirmOrderData.confirmOrderList)
                let orderShopList = []
                this.confirmOrderData.confirmOrderList.forEach(shopData => {
                    let shopCouponId = null;
                    let shopCouponDiscount = 0;
                    if (shopData.coupon.couponId) {
                        shopCouponId = shopData.coupon.couponId
                        shopCouponDiscount = shopData.coupon.discount
                    }
                    let orderShop = {
                        shopId: shopData.shopId,
                        shopCouponId: shopCouponId,
                        message: shopData.message,
                        couponPrice: shopCouponDiscount,
                        actualPrice: shopData.totalPrice - shopCouponDiscount,
                        totalPrice: shopData.totalPrice,
                        invoice: shopData.invoice,//是否开发票
                        orderGoodsList: [],
                    }
                    shopData.goodsList.forEach(goods => {
                        let orderGoods = {
                            skuId: goods.skuId,
                            goodsId: goods.goodsId,
                            title: goods.name,
                            num: goods.num,
                            price: goods.price,
                            brandId: goods.brandId,
                            spec: goods.selectedParam,
                            specDisplayName: goods.specStr,
                            picture: goods.picture,
                            integral: goods.giveIntegral === true ? goods.price / 2 : 0
                        }
                        orderShop.orderGoodsList.push(orderGoods)
                    })
                    orderShopList.push(orderShop)
                })
                let orderData = {
                    order: {
                        address: this.selectedAddress.province + this.selectedAddress.city + this.selectedAddress.area + this.selectedAddress.address,
                        consignee: this.selectedAddress.name,
                        integral: this.useIntegral ? this.confirmOrderData.integral / 100 : 0,
                        mobile: this.selectedAddress.mobile,
                        sysCouponId: this.sysCoupon.couponId ? this.sysCoupon.couponId : null,
                        useIntegral: this.useIntegral
                    },
                    orderShopList: orderShopList
                }
                this.orderData = orderData
                if (!orderData.order.address || orderData.order.address.trim() === "") {
                    this.$message.warning("请选择收货地址，如没有请设置收货地址");
                    return;
                }
                console.log(this.orderData)
                orderApi.commitOrder(this.orderData).then(resp => {
                    if (resp.data.flag) {
                        this.$router.push(`/order_pay?orderId=${resp.data.data}`)
                    }
                })
            },
            useIntegralChange(value) {
                if (value.target.checked) {
                    this.orderTotalPrice -= this.confirmOrderData.integral / 100;
                } else {
                    this.orderTotalPrice += this.confirmOrderData.integral / 100;
                }
                this.useIntegral = value.target.checked;
            },
            /**
             * 选择店铺优惠券
             */
            shopCouponChange(couponId, shopId) {
                let confirmOrderList = []
                Object.assign(confirmOrderList, this.confirmOrderData.confirmOrderList)
                let target = confirmOrderList.find(order => order.shopId === shopId)
                if (couponId === '-1') {
                    if (target.coupon.couponId) {
                        this.orderTotalPrice += target.coupon.discount
                    }
                    target.coupon = {}
                    let useShopCoupon = false;
                    this.confirmOrderData.confirmOrderList.forEach(item => {
                        if (item.coupon.couponId) {
                            useShopCoupon = true;
                        }
                    })
                    this.useShopCoupon = useShopCoupon;
                    console.log(this.useShopCoupon)
                } else {
                    if (target.coupon.couponId) {
                        // 如果之前已选了，则先将价格按之前选的优惠券加回去
                        this.orderTotalPrice += target.coupon.discount
                    }
                    let targetCoupon = target.couponList.find(coupon => coupon.couponId === couponId)
                    target.coupon = targetCoupon;
                    console.log(targetCoupon)
                    this.orderTotalPrice -= target.coupon.discount
                    this.useShopCoupon = true
                }

                console.log(this.useShopCoupon)
                this.confirmOrderData.confirmOrderList = confirmOrderList
            },
            sysCouponChange(couponId) {
                if (couponId === "-1") {
                    // 不使用优惠
                    this.useSysCoupon = false;
                    if (this.sysCoupon.couponId) {
                        this.orderTotalPrice += this.sysCoupon.discount
                    }
                    this.sysCoupon = {}
                    return;
                }
                let target = this.confirmOrderData.sysCouponList.find(coupon => coupon.couponId === couponId)
                if (target) {
                    if (this.sysCoupon.couponId) {
                        this.orderTotalPrice += this.sysCoupon.discount
                    }
                    this.sysCoupon = target;
                    this.orderTotalPrice -= this.sysCoupon.discount
                    this.useSysCoupon = true
                }
            },
            loadOrder() {
                if (this.carIds.length > 0) {
                    orderApi.confirmOrderData(this.carIds).then(resp => {
                        if (resp.data.flag) {
                            let i = 0;
                            let orderTotalPrice = 0;//订单总金额
                            let goodsCount = 0
                            let hasShopCoupon=false;
                            resp.data.data.confirmOrderList.forEach(order => {
                                if (order.couponList&&order.couponList.length>0){
                                    hasShopCoupon=true
                                }
                                //当前店铺订单总金额
                                let shopTotalPrice = 0;
                                order.goodsList.forEach(goods => {
                                    shopTotalPrice += goods.totalPrice
                                    goodsCount++;
                                })
                                orderTotalPrice += shopTotalPrice;
                                order.totalPrice = shopTotalPrice //店铺合计
                                order.message = ""
                                order.invoice = false //是否开发票
                                if (order.couponList && order.couponList.length > 0) {
                                    for (let j = 0; j < order.couponList.length; j++) {

                                        if (order.couponList[j].max === true) {
                                            //默认选择最大优惠金额的券
                                            order.coupon = order.couponList[j]
                                            orderTotalPrice -= order.coupon.discount;
                                            this.couponMax[i] = order.couponList[j].couponId;
                                            break;
                                        }
                                    }
                                } else {
                                    this.couponMax[i] = '-1'
                                    order.coupon = {}
                                }
                                i++;
                            })
                            if (hasShopCoupon){
                                this.useShopCoupon=true;
                            }else if (resp.data.data.sysCouponList&&resp.data.data.sysCouponList.length>0){
                                this.useSysCoupon=true;
                            }
                            this.goodsCount = goodsCount;
                            this.orderTotalPrice = orderTotalPrice;
                            this.confirmOrderData = resp.data.data
                            console.log(this.confirmOrderData)

                        }
                    })
                }
            },
            selectAddress(address) {
                this.selectedAddress = address;
                this.orderData.order.consignee = address.name;
                this.orderData.order.mobile = address.mobile;
                this.orderData.order.address = address.province + address.city + address.area + address.address;
                console.log(this.selectedAddress)
            },
            loadAddress() {
                addressApi.userAddressData().then(resp => {
                    if (resp.data.flag) {
                        this.addressList = resp.data.data
                        if (this.addressList.length > 0) {
                            let defaultAdd = this.addressList.find(address => address.isDefault === true)
                            if (defaultAdd) {
                                this.selectedAddress = defaultAdd
                            } else {
                                this.selectedAddress = this.addressList[0]
                            }
                        }
                    }
                })
            },
            /**
             * 表单修改省市区的回调
             * @param areaIds
             */
            modifyAreas(areaIds) {
                this.addressForm.provinceId = areaIds.province
                this.addressForm.cityId = areaIds.city
                this.addressForm.areaId = areaIds.area
            },
            openAddressForm(record) {

                if (record) {
                    let address = {}
                    Object.assign(address, record);
                    address.tempArea = [address.provinceId, address.cityId, address.areaId]
                    delete address.province
                    delete address.city
                    delete address.area
                    this.addressForm = address;
                    console.log(this.addressForm)
                    console.log(address)
                } else {
                    this.reset()
                }

                this.addressModelVisible = false
                this.addressModelVisible = true
            },
            reset() {
                this.addressForm = {
                    id: undefined,
                    name: "",
                    address: "",
                    provinceId: undefined,
                    cityId: undefined,
                    areaId: undefined,
                    mobile: "",
                    zipCode: "",
                    label: "",
                    tempArea: [],
                    isDefault: false,
                }
            },
            closeForm() {
                this.addressModelVisible = false
            },
            toShoppingCar() {
                this.$router.push("/cart_index")
            }
        }
    }
</script>

<style scoped>

    .address-header-text {
        font-size: 14px;
        font-weight: 700;
        color: #333;
        line-height: 25px;
        margin-top: 20px;

    }

    .address-card {
        border: 1px solid red;
        background: white;
        position: relative;
        z-index: 2;
        padding: 11px 0px 11px 15px;
        overflow: hidden;
        display: block;
        cursor: pointer;
        color: #666;
        font-size: 12px;
        line-height: 1.5;
        width: 250px;
        height: 140px;
    }


    .address-area {
        border-bottom: 0.1px solid #fcdfe0;
        margin-bottom: 5px;
        padding-bottom: 5px;
        font-weight: 500;
    }

    .showAll :hover {
        color: #E4393C;
    }

    .showAll a {
        color: #f57d7f;
    }

    .goodsName {
        color: #666;
        font-size: 12px;

    }

    .price {
        color: #E2231A;
        font-weight: 700;
        padding: 5px 10px;
        width: 80%;
        text-align: center;
    }

    .tip {
        font-size: 12px;
        color: #e20606;
    }

    .coupon-select {
        width: 120px;
    }

    .shopName {
        font-size: 14px;
        font-weight: 600;
        margin-bottom: 10px;
    }

    .integral-checkbox {
        width: 900px;
        background: white;
        height: 90px;
        padding-top: 13px;

    }

    .commit-contaniner {
        background: white;
        width: 900px;
        margin-top: 20px;
        height: auto;
        padding: 20px 0;
    }

    .commit-title {
        font-weight: 600;
        margin-left: 10px;
    }

    .address-info {
        font-size: 13px;
    }

    .commit-btn {
        float: right;
        background: #FF0036;
        padding: 14px 21px;
        color: white;
        font-size: 14px;
        cursor: pointer;
        font-weight: 700;

    }
</style>